package com.jqsoft.launcher.activity.gairui;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.garea.medical.MedicalFactory;
import com.garea.medical.ecg.IEcg;
import com.garea.medical.ecg.IEcg.EcgListener;
import com.garea.medical.ecg.IEcgAnalysisResult;
import com.garea.medical.ecg.IEcgData;
import com.garea.medical.ecg.IEcgState;
import com.garea.util.android.medical.player.ecg.GEcgWavePlayer;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.PersonnelInformation;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.EcgUtil;

import java.util.ArrayList;
import java.util.List;

public class EcgExample extends JQActivity {
	private IEcg mEcg;

	public static final int DAOLIAN_NUMBER = 12;

	//心电分析的结果
	private IEcgAnalysisResult ecgAnalysisResult;
	//心电检测测量的数据
	private short[] ecgTenSecondsData = null;
	
	private TextView tvHr;
	private SurfaceView sv;
	private GEcgWavePlayer player;
	
	private Spinner spHp, spLp, spNotch;
	private int hpValue, lpValue, notchValue;
	
	private Button btnStart, btnCancel, btnAnalyse, btnClear;
	private static final byte USER_INFO_GENDER_MALE = 0;//男性
	private static final byte USER_INFO_GENDER_FEMALE = 1;//女性
	private IEcgState mState;
	/**
	 * 心电分析相关
	 */
	private ProgressDialog aProDialog;
	private Dialog dResult;
	private TextView txtRHr, txtQRS, txtPR, txtQtQtc;
	private TextView txtPT, txtRv5Sv1, txtRv5pSv1, txtPWidth;
	private LinearLayout layRItems;

	private PersonnelInformation personInfo;
	
	private OnItemSelectedListener listener = new OnItemSelectedListener() {

		/**
		 * 点击滤波下拉框时，设置心电滤波参数
		 */
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			int hp, lp, notch;
			switch (spHp.getSelectedItemPosition()) {
			case 0:
				hp = IEcg.ECG_FILTER_HP_005;
				break;
			case 1:
				hp = IEcg.ECG_FILTER_HP_015;
				break;
			case 2:
				hp = IEcg.ECG_FILTER_HP_025;
				break;
			case 3:
				hp = IEcg.ECG_FILTER_HP_050;
				break;
			default:
				hp = IEcg.ECG_FILTER_HP_CLOSE;
				break;
			}
			hpValue=hp;
			
			switch (spLp.getSelectedItemPosition()) {
			case 0:
				lp = IEcg.ECG_FILTER_LP_20HZ;
				break;
			case 1:
				lp = IEcg.ECG_FILTER_LP_30HZ;
				break;
			case 2:
				lp = IEcg.ECG_FILTER_LP_40HZ;
				break;
			default:
				lp = IEcg.ECG_FILTER_LP_CLOSE;
				break;
			}
			lpValue=lp;
			
			switch (spNotch.getSelectedItemPosition()) {
			case 0:
				notch = IEcg.ECG_FILTER_NOTCH_50HZ;
				break;
			case 1:
				notch = IEcg.ECG_FILTER_NOTCH_60HZ;
				break;
			default:
				notch = IEcg.ECG_FILTER_NOTCH_CLOSE;
				break;
			}
			notchValue=notch;
			
			mEcg.setFilter(hp, lp, notch);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};
	
	/**
	 * 初始化心电播放器
	 */
	private void initPlayer() {
		sv = (SurfaceView) this.findViewById(R.id.svWave);
		TableLayout layout = (TableLayout)this.findViewById(R.id.layWaveCanvas);
		player = new GEcgWavePlayer(layout, sv, this);
	}

	private void initPersonInfo(){
		Intent intent = getIntent();
		if (intent!=null){
			personInfo = (PersonnelInformation) intent.getSerializableExtra("personInfo");
		}
	}

	private int getAge(){
		int age =20;
		if (personInfo!=null){
			age = CommonUtil.calcAge2(personInfo
					.getdBirthday());
		}
		return age;
	}

	private byte getSex(){
		byte sex = USER_INFO_GENDER_MALE;
		if (personInfo!=null){
			String sexString = personInfo.getsSexName();
			if ("女".equals(sexString)){
				sex=USER_INFO_GENDER_FEMALE;
			}
		}
		return sex;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.example_ecg);

		initPersonInfo();
		
		tvHr = (TextView) this.findViewById(R.id.tvHr);
		
		String[] sHp={"0.05Hz", "0.15Hz", "0.25Hz", "0.50Hz", "关闭"};
		String[] sLp = {"20Hz","30Hz","40Hz","关闭"};
		String[] sNotch = {"50Hz", "60Hz", "关闭"};
		
		ArrayAdapter<String> aHp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sHp);
		ArrayAdapter<String> aLp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sLp);
		ArrayAdapter<String> aNotch = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sNotch);
		aHp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		aLp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		aNotch.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spHp = (Spinner) this.findViewById(R.id.spHp);
		spLp = (Spinner) this.findViewById(R.id.spLp);
		spNotch = (Spinner) this.findViewById(R.id.spNotch);

		hpValue = IEcg.ECG_FILTER_HP_005;
		lpValue = IEcg.ECG_FILTER_LP_CLOSE;
		notchValue = IEcg.ECG_FILTER_NOTCH_CLOSE;

		spHp.setAdapter(aHp);
		spLp.setAdapter(aLp);
		spNotch.setAdapter(aNotch);
		
		btnStart = (Button) this.findViewById(R.id.btnEcgStartRecord);
		btnCancel = (Button) this.findViewById(R.id.btnEcgCancelRecord);
		btnAnalyse = (Button) this.findViewById(R.id.btnEcgAnalyseRecord);
		btnClear = (Button) this.findViewById(R.id.btnEcgClearData);
		
		setPlayState();
		btnClear.setOnClickListener(new OnClickListener() {
			/**
			 * 心电清零操作
			 */
			@Override
			public void onClick(View v) {
				mEcg.clearToZero();
			}
		});
		
		btnStart.setOnClickListener(new OnClickListener() {

			/**
			 * 开始记录心电数据
			 */
			@Override
			public void onClick(View v) {
				player.startRecord();
				setRecordState();
			}
			
		});
		
		btnCancel.setOnClickListener(new OnClickListener() {
			/**
			 * 取消记录心电数据
			 */
			@Override
			public void onClick(View v) {
				player.cancelRecord();
				setPlayState();
			}
		});
		
		btnAnalyse.setOnClickListener(new OnClickListener() {
			/**
			 * 分析记录的心电数据
			 */
			@Override
			public void onClick(View v) {
//				mEcg.analyseEcg(player.getRecords());
//				IEcg.ECG_ANALYSIS_MODE_3;// 按3导6条线分析的标志 （也就是6导）
//				IEcg.ECG_ANALYSIS_MODE_12;// 按12导12条线分析的标志
				byte mode = IEcg.ECG_ANALYSIS_MODE_12;
				//参数说明： 心电数据 、 年龄、性别、心电导数标志
				int age = getAge();
				byte sex = getSex();
				mEcg.analyseEcg(player.getRecords(),age, sex,mode);
//				mEcg.analyseEcg(player.getRecords(),20, USER_INFO_GENDER_MALE,mode);
			}
		});
		
		initPlayer();
		
		initEcg();
	}

    @Override
    protected int getContentLayout() {
        return R.layout.example_ecg;
    }

    @Override
    protected void initGui() {

    }

    @Override
    protected void initAction() {
        setGoBack();
    }

    @Override
    protected void initData() {
        setTitle("心电分析");

    }

    private void setPlayState() {
		btnStart.setEnabled(true);
		btnCancel.setEnabled(false);
		btnAnalyse.setEnabled(false);
	}
	
	private void setRecordState() {
		btnStart.setEnabled(false);
		btnCancel.setEnabled(true);
		btnAnalyse.setEnabled(false);
	}
	
	private void setAnalyseState() {
		btnStart.setEnabled(true);
		btnCancel.setEnabled(false);
		btnAnalyse.setEnabled(false);
	}
	
	private void initResultDialog() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout layResult = (LinearLayout) inflater.inflate(R.layout.g_measurer_ecg_ana, null, false);
//		int rID = this.getResources().getIdentifier("dialog", "style", "com.jqsoft.launcher");
		dResult = new Dialog(this, R.style.dialog);
		dResult.setContentView(layResult);
		
		txtRHr = (TextView) dResult.findViewById(R.id.txtEcgRHr);
		txtQRS = (TextView) dResult.findViewById(R.id.txtEcgRQrs);
		txtPR = (TextView) dResult.findViewById(R.id.txtEcgRPr);
		txtQtQtc = (TextView) dResult.findViewById(R.id.txtEcgRQTQTc);
		txtPT = (TextView) dResult.findViewById(R.id.txtEcgRPQRST);
		txtRv5Sv1 = (TextView) dResult.findViewById(R.id.txtEcgRRV5oSV1);
		txtRv5pSv1 = (TextView) dResult.findViewById(R.id.txtEcgRRV5aSV1);
		txtPWidth = (TextView) dResult.findViewById(R.id.txtEcgRPWidth);
		
		Button btnRecordOK = (Button) dResult.findViewById(R.id.btnEcgResultOK);
		btnRecordOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (dResult != null) {
					dResult.dismiss();
				}
				deliverEcgAnalysisResult(ecgAnalysisResult);
			}
		});
		
		layRItems = (LinearLayout) dResult.findViewById(R.id.layEcgRDiagnoseItem);
	}

	private void deliverEcgAnalysisResult(IEcgAnalysisResult result){
		if (result==null){
			return;
		} else {
			Intent intent = new Intent();
//			intent.putExtra(EcgContent.ECG_DATA, result.getPom());
			intent.putExtra(EcgContent.ECG_DATA, ecgTenSecondsData);

			 intent.putExtra(EcgContent.ECG_CONF_HP, hpValue);
			 intent.putExtra(EcgContent.ECG_CONF_LP, lpValue);
			 intent.putExtra(EcgContent.ECG_CONF_NOTCH, notchValue);

			intent.putExtra(EcgContent.ECG_HR, result.getHR());
			intent.putExtra(EcgContent.ECG_P_AXIS, result.getPAxis());
			intent.putExtra(EcgContent.ECG_QRS_AXIS, result.getQRSAxis());
			intent.putExtra(EcgContent.ECG_T_AXIS, result.getTAxis());
			intent.putExtra(EcgContent.ECG_PR_INTERVAL, result.getPRInterval());
			intent.putExtra(EcgContent.ECG_QRS_DURATION, result.getQRSDuration());
			intent.putExtra(EcgContent.ECG_QTD, result.getQTd());
			intent.putExtra(EcgContent.ECG_QTC, result.getQTc());
			intent.putExtra(EcgContent.ECG_RV5, result.getRV5());
			intent.putExtra(EcgContent.ECG_SV1, result.getSV1());
			intent.putExtra(EcgContent.ECG_RV5_SV1, result.getRV5SV1());
			intent.putExtra(EcgContent.ECG_P_WIDTH, result.getPWidth());
			intent.putExtra(EcgContent.ECG_P_EXIST, (byte)(result.getPExist()));

			int[] resultCodes = getEcgResultCodeIntArray(result);
			intent.putExtra(EcgContent.ECG_RESULT_CODE, resultCodes);
			List<String> resultTextList = result.getResultText();
//			intent.putStringArrayListExtra(EcgContent.ECG_RESULT_TEXT, (ArrayList<String>) resultTextList);
			intent.putExtra(EcgContent.ECG_RESULT_TEXT, (ArrayList<String>) resultTextList);

			setResult(RESULT_OK, intent);
			finish();
		}
	}

	private int[] getEcgResultCodeIntArray(IEcgAnalysisResult r){
		int[] result = new int[]{};
		if (r==null){
			return result;
		} else {
//			int [] keyArray = new int[]{
//				G_ECG_LEAD_I,
//				G_ECG_LEAD_II,
//				G_ECG_LEAD_C1,
//				G_ECG_LEAD_C2,
//				G_ECG_LEAD_C3,
//				G_ECG_LEAD_C4,
//				G_ECG_LEAD_C5,
//				G_ECG_LEAD_C6,
//				G_ECG_LEAD_III,
//				G_ECG_LEAD_AVL,
//				G_ECG_LEAD_AVR,
//				G_ECG_LEAD_AVF
//			};
			int[] ia = new int[10];
			for (int i = 0; i < ia.length; ++i){
				ia[i] = (int)r.getResultCode(i);
			}
//			for (int i = 0; i < keyArray.length; ++i){
//				int it = (int) r.getResultCode(keyArray[i]);
//				ia[i] = it;
//			}
			return ia;
		}
	}

	private List<IEcgData> getRecords(){
		if (player==null){
			return  null;
		} else {
			return player.getRecords();
		}
	}

	/**
	 * 第一秒的 1导500个点 2导的500个点 3导的500个点。。。。。12导的500个点
	 然后是 第二秒
	 * @return
	 */
	private short[] getMergedShortArrayFromRecords(){
		List<IEcgData> dataList = getRecords();
		if (dataList==null){
			return null;
		} else {
			List<short[]> result = new ArrayList<>();
			for (int i = 0; i < dataList.size(); ++i){
				IEcgData data = dataList.get(i);
				int count1 = data.getLeadDataCount();
				int count2 = data.getLeadCount();
				short[] one = data.getLeadData(IEcgData.G_ECG_LEAD_I);
				short[] two = data.getLeadData(IEcgData.G_ECG_LEAD_II);
				short[] three = data.getLeadData(IEcgData.G_ECG_LEAD_III);
				short[] four = data.getLeadData(IEcgData.G_ECG_LEAD_AVR);
				short[] five = data.getLeadData(IEcgData.G_ECG_LEAD_AVL);
				short[] six = data.getLeadData(IEcgData.G_ECG_LEAD_AVF);
				short[] seven = data.getLeadData(IEcgData.G_ECG_LEAD_C1);
				short[] eight = data.getLeadData(IEcgData.G_ECG_LEAD_C2);
				short[] nine = data.getLeadData(IEcgData.G_ECG_LEAD_C3);
				short[] ten = data.getLeadData(IEcgData.G_ECG_LEAD_C4);
				short[] eleven = data.getLeadData(IEcgData.G_ECG_LEAD_C5);
				short[] twelve = data.getLeadData(IEcgData.G_ECG_LEAD_C6);
				List<short[]> list = new ArrayList<>();
				list.add(one);
				list.add(two);
				list.add(three);
				list.add(four);
				list.add(five);
				list.add(six);
				list.add(seven);
				list.add(eight);
				list.add(nine);
				list.add(ten);
				list.add(eleven);
				list.add(twelve);
				short[] shortArray = EcgUtil.mergeShortArrayList(list);
				result.add(shortArray);
			}
			short[] ultimateResult = EcgUtil.mergeShortArrayList(result);
			return ultimateResult;
		}
	}
	
	private void initEcg() {
		mEcg = MedicalFactory.createLocalEcg();
		mEcg.addEcgListener(new EcgListener() {

			/**
			 * 获取到心电滤波设置参数
			 */
			@Override
			public void onGetFilter(int hp, int lp, int notch) {
				Log.i("EcgExample", "当前心电滤波:" + hp + "," + lp + "," + notch);
				
				switch (hp) {
				case IEcg.ECG_FILTER_HP_005:
					
					spHp.setSelection(0);
					break;
					
				case IEcg.ECG_FILTER_HP_015:
					spHp.setSelection(1);
					break;
					
				case IEcg.ECG_FILTER_HP_025:
					spHp.setSelection(2);
					break;
					
				case IEcg.ECG_FILTER_HP_050:
					spHp.setSelection(3);
					break;
					
				default:
					spHp.setSelection(4);
					break;
				}
				
				switch (lp) {
				case IEcg.ECG_FILTER_LP_20HZ:
					spLp.setSelection(0, true);
					break;
				case IEcg.ECG_FILTER_LP_30HZ:
					spLp.setSelection(1, true);
					break;
				case IEcg.ECG_FILTER_LP_40HZ:
					spLp.setSelection(2, true);
					break;
					
				default:
					spLp.setSelection(3, true);
					break;
				}
				
				switch (notch) {
				case IEcg.ECG_FILTER_NOTCH_50HZ:
					spNotch.setSelection(0, true);
					break;
					
				case IEcg.ECG_FILTER_NOTCH_60HZ:
					spNotch.setSelection(1, true);
					break;
					
				default:
					spNotch.setSelection(2, true);
					break;
				}
				
				Log.i("SSS", "Selection:" + spHp.getSelectedItemPosition() + "," + spLp.getSelectedItemPosition()
						+ "," + spNotch.getSelectedItemPosition());
				
				spHp.setOnItemSelectedListener(listener);
				spLp.setOnItemSelectedListener(listener);
				spNotch.setOnItemSelectedListener(listener);
			}

			/**
			 * 心电分析结束
			 * 
			 * isSuccess为false时，分析失败，r参数无效
			 */
			@Override
			public void onAnalyseCompleted(boolean isSuccess, IEcgAnalysisResult r) {
				Log.i("EcgExample", "分析结束");
				
				if (aProDialog != null) {
					aProDialog.dismiss();
				}
				
				if (!isSuccess) {
					Toast.makeText(EcgExample.this, "分析失败",
							Toast.LENGTH_SHORT).show();
				} else {
					EcgExample.this.ecgAnalysisResult = r;
					EcgExample.this.ecgTenSecondsData = getMergedShortArrayFromRecords();
					if (dResult == null) {
						initResultDialog();
					}
					txtRHr.setText(Integer.toString((int)r.getHR()) + "bpm");
					txtQRS.setText(Integer.toString((int)r.getQRSDuration()) + "ms");
					txtPR.setText(Integer.toString((int)r.getPRInterval()) + "ms");
					txtQtQtc.setText(Integer.toString((int)r.getQTd()) + "ms/" + Integer.toString((int)r.getQTc()) + "ms");
					txtPT.setText(Integer.toString((int)r.getPAxis()) + "度/" + Integer.toString((int)r.getQRSAxis()) + "度/" + Integer.toString((int)r.getTAxis()) + "度");
					txtRv5Sv1.setText(Float.toString(Math.abs(r.getRV5())) + "mV/" + Float.toString(Math.abs(r.getSV1())) + "mV");
					txtRv5pSv1.setText(Float.toString(r.getRV5SV1()) + "mV");
					txtPWidth.setText(Float.toString(r.getPWidth()) + "mV");
					layRItems.removeAllViews();
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);

					for (String rText : r.getResultText()) {
						TextView txtMsg = new TextView(EcgExample.this);
						txtMsg.setText(rText);
						txtMsg.setTextColor(Color.WHITE);
						txtMsg.setTextSize(16);
						txtMsg.setLayoutParams(param);
						layRItems.addView(txtMsg);
					}
					dResult.show();
				}
				player.cancelRecord();
				setPlayState();
			}

			/**
			 * 开始分析心电数据
			 */
			@Override
			public void onAnalysingEcg() {
				Log.i("EcgExample", "开始分析心电数据");
				
				if (aProDialog == null) {
					aProDialog = ProgressDialog.show(EcgExample.this, "心电分析", "分析中...");
				} else {
					aProDialog.show();
				}
			}

			/**
			 * 接收心电数据
			 */
			@Override
			public void onReceivedData(IEcgData d) {
				if (d.getHr() > -1) {
					tvHr.setText(Integer.toString(d.getHr()));
				} else {
					tvHr.setText("---");
				}
				
				if (player.getRecordsSeconds() == 10) {
					if (!btnAnalyse.isEnabled())
						btnAnalyse.setEnabled(true);
				} else {
					if (btnAnalyse.isEnabled())
						btnAnalyse.setEnabled(false);
				}
				player.pushEcgData(d);
			}

			@Override
			public void onReceivedState(IEcgState nState) {
//				nState.hasChanged(nextState);//用来判断 和上一个状态进行比较  
//				nState.hasLeadOff(); 导联 线有一个 脱落就会 返回true
//				nState.hasLeadC1Off();//判断 单个c1 导联是否脱落  其他 导联线 都有对应的方法
				
//				开发时 如果是 12导模式 可使用 nState.hasLeadOff();  来判断 是否有导联线脱落
//				如果是6导模式  则只需要判读 L、F、R 这三条导联线是否脱落	if (nState.hasLeadFOff() ||  nState.hasLeadLOff() || nState.hasLeadROff() ) { 有脱落}

//                if (nState.hasLeadFOff() ||  nState.hasLeadLOff() || nState.hasLeadROff() ) {
//
//                }
			}
			
			@Override
			public void onInited() {
				Log.i("EcgExample", "心电初始化成功");
				mEcg.start();
			}
			
			@Override
			public void onStarted() {
				Log.i("EcgExample", "心电已开始");
				/**
				 * 获取心电滤波设置
				 */
				mEcg.getFilter();
			}
		
		});
	}
	
	@Override
	public void onStart() {
		super.onStart();
		mEcg.init();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public void onStop() {
		super.onStop();
		mEcg.stop();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();//添加此行
//		super.onStop();//注释此行
		mEcg.uninit();
	}
}
